package com.zhentao.controller;

import cn.hutool.json.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zhentao.api.user.UserApi;
import com.zhentao.api.userCoupon.UserCouponApi;
import com.zhentao.config.AliPayConfig;
import com.zhentao.mapper.ChargePayCouponMapper;
import com.zhentao.model.common.pojo.pay.ChargePayCoupon;
import com.zhentao.model.common.pojo.pay.ChargePayOrder;
import com.zhentao.model.common.pojo.users.param.UserBalanceParam;
import com.zhentao.service.IChargePayOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

//  https://natapp.cn/
// ekihat7647@sandbox.com
@RestController
@RequestMapping("/alipay")
public class AliPayController {

    // 支付宝沙箱网关地址
    private static final String GATEWAY_URL = "https://openapi-sandbox.dl.alipaydev.com/gateway.do";
    private static final String FORMAT = "JSON";
    private static final String CHARSET = "UTF-8";
    //签名方式
    private static final String SIGN_TYPE = "RSA2";

    @Resource
    private AliPayConfig aliPayConfig;

    @Resource
    private IChargePayOrderService chargePayOrderService;

    @Autowired
    private UserApi userApi;
    @Autowired
    private UserCouponApi userCouponApi;
    @GetMapping("/pay")  //  /alipay/pay?orderNo=xxx
    public void pay(@RequestParam("orderNo") Long orderNo, HttpServletResponse httpResponse) throws Exception {
        // 查询订单信息
        ChargePayOrder chargePayOrder = chargePayOrderService.getOne(Wrappers.<ChargePayOrder>lambdaQuery().eq(ChargePayOrder::getOrderNo, orderNo));
        if (chargePayOrder == null) {
            return;
        }
        // 1. 创建Client，通用SDK提供的Client，负责调用支付宝的API
        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, aliPayConfig.getAppId(),
                aliPayConfig.getAppPrivateKey(), FORMAT, CHARSET, aliPayConfig.getAlipayPublicKey(), SIGN_TYPE);

        // 2. 创建 Request并设置Request参数
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();  // 发送请求的 Request类
        request.setNotifyUrl(aliPayConfig.getNotifyUrl());
        JSONObject bizContent = new JSONObject();
        bizContent.set("out_trade_no", orderNo);  // 我们自己生成的订单编号
        bizContent.set("total_amount", chargePayOrder.getAmount()); // 订单的总金额
        bizContent.set("subject", chargePayOrder.getChannelId());   // 支付的名称
        bizContent.set("product_code", "FAST_INSTANT_TRADE_PAY");  // 固定配置
        request.setBizContent(bizContent.toString());
        request.setReturnUrl("http://localhost:8080/user/charge/money/success"); // 支付完成后自动跳转到本地页面的路径
        // 执行请求，拿到响应的结果，返回给浏览器
        String form = "";
        try {
            form = alipayClient.pageExecute(request).getBody(); // 调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        httpResponse.setContentType("text/html;charset=" + CHARSET);
        httpResponse.getWriter().write(form);// 直接将完整的表单html输出到页面
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
    }
    @Resource
    private ChargePayCouponMapper chargePayCouponMapper;
    @PostMapping("/notify")  // 注意这里必须是POST接口
    public void payNotify(HttpServletRequest request) throws Exception {
        if (request.getParameter("trade_status").equals("TRADE_SUCCESS")) {
            System.out.println("=========支付宝异步回调========");

            Map<String, String> params = new HashMap<>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (String name : requestParams.keySet()) {
                params.put(name, request.getParameter(name));
            }

            String sign = params.get("sign");
            String content = AlipaySignature.getSignCheckContentV1(params);
            boolean checkSignature = AlipaySignature.rsa256CheckContent(content, sign, aliPayConfig.getAlipayPublicKey(), "UTF-8"); // 验证签名
            // 支付宝验签
            if (checkSignature) {
                // 验签通过
                System.out.println("交易名称: " + params.get("subject"));
                System.out.println("交易状态: " + params.get("trade_status"));
                System.out.println("支付宝交易凭证号: " + params.get("trade_no"));
                System.out.println("商户订单号: " + params.get("out_trade_no"));
                System.out.println("交易金额: " + params.get("total_amount"));
                System.out.println("买家在支付宝唯一id: " + params.get("buyer_id"));
                System.out.println("买家付款时间: " + params.get("gmt_payment"));
                System.out.println("买家付款金额: " + params.get("buyer_pay_amount"));

//                买家付款时间字符串
                String gmtPayment = params.get("gmt_payment");
                String tradeNo = params.get("trade_no");//买家在交易平台的唯一id
//                商户订单号
                String orderNo = params.get("out_trade_no");


                ChargePayOrder chargePayOrder = chargePayOrderService.getOne(Wrappers.<ChargePayOrder>lambdaQuery().eq(ChargePayOrder::getOrderNo, orderNo));
//                支付成功
                chargePayOrder.setPayStatus(2);
//                支付宝交易的凭证号
                chargePayOrder.setPayOrderNo(tradeNo);
//                转换买家付款时间
                Date gmtPaymentDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(gmtPayment);
                chargePayOrder.setCreateTime(gmtPaymentDate);
//                执行修改
                chargePayOrderService.updateById(chargePayOrder);


//                TODO 删除用户和优惠券的关联关系
                List<ChargePayCoupon> chargePayCouponList = chargePayCouponMapper
                        .selectList(Wrappers.<ChargePayCoupon>lambdaQuery().eq(ChargePayCoupon::getPayId, chargePayOrder.getId()));

                List<Integer> couponIds = chargePayCouponList.stream()
                        .map(ChargePayCoupon::getCouponId)
                        .collect(Collectors.toList());

                userCouponApi.deleteUserCoupon(couponIds, chargePayOrder.getUserId());
                //TODO 修改用户的余额并修改用户优惠卷数量
                Integer orderType = chargePayOrder.getOrderType();
                UserBalanceParam userBalanceParam = new UserBalanceParam();
                userBalanceParam.setAmount(chargePayOrder.getInitialAmount());
                userBalanceParam.setChannelId(chargePayOrder.getChannelId());
                userBalanceParam.setUserId(chargePayOrder.getUserId());
                userBalanceParam.setOrderType(orderType);
                userBalanceParam.setCouponMount(couponIds.size());
                userApi.updateBalance(userBalanceParam);
            }
        }
    }

//    /**
//     * 退款接口
//     */
//    @PutMapping("/refund")
//    public Result refund(String orderNo) {
//        Orders orders = ordersService.selectByOrderNo(orderNo);
//        if (ObjectUtil.isNull(orders)) {
//            throw new CustomException("500", "未找到订单");
//        }
//        // 1. 创建Client，通用SDK提供的Client，负责调用支付宝的API
//        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, aliPayConfig.getAppId(),
//                aliPayConfig.getAppPrivateKey(), FORMAT, CHARSET, aliPayConfig.getAlipayPublicKey(), SIGN_TYPE);
//
//        // 2. 创建 Request并设置Request参数
//        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
//        request.setNotifyUrl(aliPayConfig.getNotifyUrl());
//        JSONObject bizContent = new JSONObject();
//        bizContent.set("out_trade_no", orders.getOrderNo());  // 我们自己生成的订单编号  必须是不重复的退款订单号
//        bizContent.set("refund_amount", orders.getTotal()); // 订单的总金额
//        bizContent.set("trade_no", orders.getPayNo()); // 支付宝支付订单号
//        bizContent.set("out_request_no", IdUtil.fastSimpleUUID());   // 随机数
//        request.setBizContent(bizContent.toString());
//        try {
//            // 退款调用接口
//            AlipayTradeRefundResponse response = alipayClient.execute(request);
//            if (response.isSuccess()) {
//                System.out.println("订单号" + orderNo + "退款成功");
//            }
//            Orders dbOrder = ordersService.selectByOrderNo(orderNo);
//            dbOrder.setStatus("已退款");
//            ordersService.updateById(dbOrder);
//        } catch (AlipayApiException e) {
//            e.printStackTrace();
//            System.err.println("退款失败");
//        }
//
//        return Result.success();
//    }

}